package com.ssps.shiro.controller;

import com.ssps.entity.User;
import com.ssps.entity.UserInfo;
import com.ssps.shiro.service.Tenant2AuthService;
import com.ssps.front.tenant2.utils2.Tenant2Utils;
import org.apache.shiro.SecurityUtils;

import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: peng
 */
@Controller
@RequestMapping("auth2")
public class Tenant2AuthController {
    @Autowired
    Tenant2AuthService tenant2AuthService;

    @RequestMapping("login2")
    @ResponseBody
    public Map<String, Object> login(@RequestBody String body, HttpSession session, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        Map<String, String> parse = Tenant2Utils.parse(body);

        UsernamePasswordToken token = new UsernamePasswordToken(parse.get("phone"), parse.get("password"));
        String path = null;

        try {

            subject.login(token);
            User user = tenant2AuthService.selectByPhoneAndPassword(parse.get("phone"));
            UserInfo userInfo = tenant2AuthService.selectByUid(user.getUid());
            session.setAttribute("loginUser", user);
            session.setAttribute("loginUserInfo", userInfo);

            if (Boolean.parseBoolean(parse.get("rember"))) {
                Cookie phoneCookie = new Cookie("phone", parse.get("phone"));
                Cookie passwordCookie = new Cookie("password", parse.get("password"));
                Cookie remberCookie = new Cookie("rember", parse.get("rember"));
                phoneCookie.setMaxAge(30 * 60 * 60 * 24);
                phoneCookie.setPath("/");
                passwordCookie.setMaxAge(30 * 60 * 60 * 24);
                passwordCookie.setPath("/");

                remberCookie.setMaxAge(30 * 60 * 60 * 24);
                remberCookie.setPath("/");

                response.addCookie(passwordCookie);
                response.addCookie(phoneCookie);
                response.addCookie(remberCookie);
            }
            String rname = tenant2AuthService.getRole(user);

            map.put("rname",rname);
            map.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", false);

        } finally {
            return map;
        }

    }
}
